﻿using System.Web.Security;
using System.Web.UI.WebControls;

namespace MyLib.Web {
	public class MyUserDataParameter : Parameter {
		/// <summary>
		/// 
		/// </summary>
		public string Key { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) {
			var p = control.Page.User;
			if (p == null)
				return null;

			var id = p.Identity as FormsIdentity;
			if (id == null)
				return null;

			var ticket = id.Ticket;
			if (ticket == null)
				return null;

			var userData = ticket.UserData;

			if(string.IsNullOrEmpty(ticket.UserData))
				return null;

			var c = userData.Split('\n');
			if (c == null || c.Length == 0)
				return null;

			var fullKey = Key + "=";

			foreach (var cl in c) {
				if (cl.StartsWith(fullKey)) {
					return cl.Substring(fullKey.Length);
				}
			} // end of foreach.

			return null;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected override Parameter Clone() {
			var ret = new MyUserDataParameter();
			ret.Name = Name;
			ret.Size = Size;
			ret.Type = Type;
			ret.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
			ret.DbType = DbType;
			ret.DefaultValue = DefaultValue;
			ret.Direction = Direction;
			ret.Key = this.Key;
			return ret;
		}
	} // end of MyUserDataParameter.
}
